import java.io.*;

/**
 * Created by foredawn on 15-8-26.
 * inputStream的复用
 */
public class StreamReuse {

    static String fileName = StreamReuse.class.getClassLoader().getResource("file").getFile();

    public static void main(String[] args) throws IOException {
        markAndReset();
        byteArrayOutputStream();
    }

    public static void markAndReset() throws IOException {
        OutputStream out = null;
        try {
            try (InputStream input = new BufferedInputStream(new FileInputStream(fileName))) {
                input.mark(1);//标记允许最大字节数(复用整个流的内容)
                for (int i = 0; i < 5; i++) {
                    out = new FileOutputStream(new File(fileName + "." + i + ".out"));
                    byte[] buf = new byte[1024];
                    int len;
                    while ((len = input.read(buf)) != -1) {
                        out.write(buf);
                    }
                    input.reset();//重置流使之复用
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
        }
    }

    public static void byteArrayOutputStream() throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            try (InputStream input = new BufferedInputStream(new FileInputStream(fileName))) {
                byte[] buf = new byte[1024];
                int len;
                while ((len = input.read(buf)) != -1) {
                    out.write(buf);//写入byte数组
                }
            }
            OutputStream outputStream = null;
            for (int i = 5; i < 11; i++) {
                outputStream = new FileOutputStream(new File(fileName + "." + i + ".out"));
                outputStream.write(out.toByteArray());
            }
            if (outputStream != null)
                outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null)
                out.close();
        }
    }
}
